package com.qiudao.basestudy.exception;

import com.qiudao.basestudy.util.result.BaseResult;
import com.qiudao.basestudy.util.result.BaseResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Description: 统一异常处理器
 * @author: gdc
 * @date: 2020/3/21
 * @version 1.0
 */
@Slf4j
@ControllerAdvice
public class BizExceptionHandler {

    /**
     * 通用的异常处理方法
     * @param e         异常
     * @return          结果
     */
    @ExceptionHandler
    @ResponseBody
    public BaseResult error(Exception e){
        log.error(getMessage(e));
        return BaseResult.error();
    }

    /**-------- 指定异常处理方法 --------**/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public BaseResult error(NullPointerException e) {
        log.error(getMessage(e));
        return BaseResult.error(BaseResultEnum.NULL_POINT);
    }

    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseBody
    public BaseResult error(IndexOutOfBoundsException e) {
        log.error(getMessage(e));
        return BaseResult.error(BaseResultEnum.HTTP_CLIENT_ERROR);
    }

    /**-------- 自定义定异常处理方法 --------**/
    @ExceptionHandler(BizException.class)
    @ResponseBody
    public BaseResult error(BizException e) {
        log.error(getMessage(e));
        return BaseResult.error(e);
    }

    /**
     * 打印异常信息
     * @param e         异常信息
     * @return          结果
     */
    private String getMessage(Exception e) {
        String swStr = null;
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            swStr = sw.toString();
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
        }
        return swStr;
    }
}
